{{define "content"}}
<div x-data="pushIndexData()" class="space-y-6">
    <!-- Page Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">推送管理</h1>
            <p class="mt-1 text-sm text-gray-500">管理客户推送，查看推送记录和统计信息。</p>
        </div>
        <div class="mt-4 sm:mt-0 flex space-x-3">
            <button @click="refreshData()" 
                    :disabled="loading"
                    class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50">
                <i class="fas fa-sync-alt mr-2" :class="loading ? 'animate-spin' : ''"></i>
                刷新数据
            </button>

        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <!-- Total Push -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-paper-plane text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">总推送数</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.totalPush || '0'"></dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm">
                    <span class="text-blue-600 font-medium">今日</span>
                    <span class="text-gray-500" x-text="stats.todayPush || '0'">0</span>
                </div>
            </div>
        </div>

        <!-- Success Push -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-check-circle text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">成功推送</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.successPush || '0'"></dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm">
                    <span class="text-green-600 font-medium" x-text="(stats.successRate || 0) + '%'">0%</span>
                    <span class="text-gray-500">成功率</span>
                </div>
            </div>
        </div>

        <!-- Pending Push -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-yellow-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-clock text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">待处理</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.pendingPush || '0'"></dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm">
                    <span class="text-yellow-600 font-medium">处理中</span>
                    <span class="text-gray-500">推送</span>
                </div>
            </div>
        </div>

        <!-- Failed Push -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-red-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-times-circle text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">失败推送</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.failedPush || '0'"></dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-5 py-3">
                <div class="text-sm">
                    <span class="text-red-600 font-medium">需重试</span>
                    <span class="text-gray-500">推送</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Unpushed Customers and Quick Actions -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Unpushed Customers -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">未推送客户</h3>
                <p class="text-sm text-gray-500">点击客户可查看推荐机构并进行推送</p>
            </div>
            <div class="p-6">
                <div class="space-y-4" x-show="unpushedCustomers.length > 0">
                    <template x-for="customer in unpushedCustomers" :key="customer.id">
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-blue-300 hover:shadow-md transition-all duration-200 cursor-pointer"
                             @click="selectCustomer(customer)">
                            <div class="flex items-center justify-between">
                                <div class="flex-1">
                                    <h4 class="text-sm font-medium text-gray-900" x-text="customer.name"></h4>
                                    <div class="mt-1 text-xs text-gray-500">
                                        <span x-text="customer.city"></span> • 
                                        <span x-text="customer.subject"></span>
                                    </div>
                                    <div class="mt-1 text-xs text-gray-400">
                                        <span x-text="customer.phone"></span>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                        未推送
                                    </span>
                                    <i class="fas fa-chevron-right text-gray-400"></i>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
                <div class="text-center py-8" x-show="unpushedCustomers.length === 0">
                    <i class="fas fa-users text-4xl text-gray-400 mb-4"></i>
                    <h4 class="text-lg font-medium text-gray-900 mb-2">暂无未推送客户</h4>
                    <p class="text-gray-500 mb-4">所有客户都已完成推送</p>
                    <a href="/customers/new" class="text-blue-600 hover:text-blue-800 font-medium">
                        添加新客户 →
                    </a>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">快速操作</h3>
                <p class="text-sm text-gray-500">推送功能的快捷入口</p>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 gap-4">


                    <a href="/push/manual" 
                       class="group relative bg-white p-4 focus-within:ring-2 focus-within:ring-inset focus-within:ring-green-500 rounded-lg border border-gray-200 hover:border-green-300 hover:shadow-md transition-all duration-200">
                        <div class="flex items-center">
                            <span class="rounded-lg inline-flex p-3 bg-green-50 text-green-600 group-hover:bg-green-100">
                                <i class="fas fa-hand-pointer text-lg"></i>
                            </span>
                            <div class="ml-4">
                                <h3 class="text-sm font-medium text-gray-900">
                                    <span class="absolute inset-0" aria-hidden="true"></span>
                                    手动推送
                                </h3>
                                <p class="text-xs text-gray-500">
                                    手动选择客户和机构
                                </p>
                            </div>
                        </div>
                    </a>



                    <a href="/push/records" 
                       class="group relative bg-white p-4 focus-within:ring-2 focus-within:ring-inset focus-within:ring-orange-500 rounded-lg border border-gray-200 hover:border-orange-300 hover:shadow-md transition-all duration-200">
                        <div class="flex items-center">
                            <span class="rounded-lg inline-flex p-3 bg-orange-50 text-orange-600 group-hover:bg-orange-100">
                                <i class="fas fa-history text-lg"></i>
                            </span>
                            <div class="ml-4">
                                <h3 class="text-sm font-medium text-gray-900">
                                    <span class="absolute inset-0" aria-hidden="true"></span>
                                    推送记录
                                </h3>
                                <p class="text-xs text-gray-500">
                                    查看推送历史记录
                                </p>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Customer Selection Modal -->
    <div x-show="showCustomerModal" 
         x-transition:enter="ease-out duration-300" 
         x-transition:enter-start="opacity-0" 
         x-transition:enter-end="opacity-100" 
         x-transition:leave="ease-in duration-200" 
         x-transition:leave-start="opacity-100" 
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" 
         style="display: none;">
        <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900">推荐机构</h3>
                    <button @click="closeCustomerModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div x-show="selectedCustomer" class="mb-6">
                    <div class="bg-gray-50 rounded-lg p-4">
                        <h4 class="font-medium text-gray-900" x-text="selectedCustomer?.name"></h4>
                        <div class="mt-1 text-sm text-gray-500">
                            <span x-text="selectedCustomer?.city"></span> • 
                            <span x-text="selectedCustomer?.subject"></span> • 
                            <span x-text="selectedCustomer?.phone"></span>
                        </div>
                    </div>
                </div>

                <div x-show="recommendedPartners.length > 0" class="space-y-3">
                    <template x-for="partner in recommendedPartners" :key="partner.partner.id">
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-blue-300 transition-colors">
                            <div class="flex items-center justify-between">
                                <div class="flex-1">
                                    <h5 class="font-medium text-gray-900" x-text="partner.partner.name"></h5>
                                    <div class="mt-1 text-sm text-gray-500">
                                        <span x-text="partner.partner.city"></span> • 
                                        <span x-text="partner.partner.subjects"></span>
                                    </div>
                                    <div class="mt-1 text-xs text-gray-400">
                                        匹配原因: <span x-text="partner.reason"></span>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-3">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                        匹配度: <span x-text="partner.match_score"></span>%
                                    </span>
                                    <button @click="pushToPartner(partner.partner.id)" 
                                            :disabled="pushing"
                                            class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50">
                                        <i class="fas fa-paper-plane mr-1"></i>
                                        推送
                                    </button>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>

                <div x-show="recommendedPartners.length === 0 && !loadingRecommendations" class="text-center py-8">
                    <i class="fas fa-exclamation-triangle text-4xl text-gray-400 mb-4"></i>
                    <h4 class="text-lg font-medium text-gray-900 mb-2">暂无推荐机构</h4>
                    <p class="text-gray-500">该客户的城市和学科暂无匹配的合作机构</p>
                </div>

                <div x-show="loadingRecommendations" class="text-center py-8">
                    <i class="fas fa-spinner fa-spin text-4xl text-gray-400 mb-4"></i>
                    <p class="text-gray-500">正在查找推荐机构...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function pushIndexData() {
        return {
            loading: false,
            pushing: false,
            loadingRecommendations: false,
            showCustomerModal: false,
            selectedCustomer: null,
            stats: {
                totalPush: 0,
                successPush: 0,
                failedPush: 0,
                pendingPush: 0,
                successRate: 0,
                todayPush: 0
            },
            unpushedCustomers: [],
            recommendedPartners: [],
            
            init() {
                this.loadStats();
                this.loadUnpushedCustomers();
            },
            
            async loadStats() {
                this.loading = true;
                try {
                    const token = localStorage.getItem('token');
                    const response = await fetch('/api/v1/push/stats', {
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            this.stats = data.data;
                        }
                    }
                } catch (error) {
                    console.error('Failed to load push stats:', error);
                } finally {
                    this.loading = false;
                }
            },
            
            async loadUnpushedCustomers() {
                try {
                    const token = localStorage.getItem('token');
                    const response = await fetch('/api/v1/customers?pushed=false&size=10', {
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            this.unpushedCustomers = data.data.items || [];
                        }
                    }
                } catch (error) {
                    console.error('Failed to load unpushed customers:', error);
                }
            },
            
            async selectCustomer(customer) {
                this.selectedCustomer = customer;
                this.showCustomerModal = true;
                this.loadingRecommendations = true;
                this.recommendedPartners = [];
                
                try {
                    const token = localStorage.getItem('token');
                    const response = await fetch(`/api/v1/push/recommended/${customer.id}`, {
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            this.recommendedPartners = data.data || [];
                        }
                    }
                } catch (error) {
                    console.error('Failed to load recommended partners:', error);
                    showToast('获取推荐机构失败', 'error');
                } finally {
                    this.loadingRecommendations = false;
                }
            },
            
            async pushToPartner(partnerId) {
                if (!this.selectedCustomer) return;
                
                this.pushing = true;
                try {
                    const token = localStorage.getItem('token');
                    const response = await fetch('/api/v1/push/manual', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + token
                        },
                        body: JSON.stringify({
                            customer_id: this.selectedCustomer.id,
                            partner_id: partnerId,
                            notes: '通过推送管理页面手动推送'
                        })
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            showToast('推送成功', 'success');
                            this.closeCustomerModal();
                            this.refreshData();
                        } else {
                            showToast(data.message || '推送失败', 'error');
                        }
                    } else {
                        showToast('推送失败', 'error');
                    }
                } catch (error) {
                    console.error('Push failed:', error);
                    showToast('推送失败', 'error');
                } finally {
                    this.pushing = false;
                }
            },
            
            closeCustomerModal() {
                this.showCustomerModal = false;
                this.selectedCustomer = null;
                this.recommendedPartners = [];
            },
            
            async refreshData() {
                await Promise.all([
                    this.loadStats(),
                    this.loadUnpushedCustomers()
                ]);
                showToast('数据已刷新', 'success');
            }
        }
    }
</script>
{{end}}